//
//  ChatRecent.m
//  YouYunSDKDemo
//
//  Created by fusuwei on 14-11-18.
//  Copyright (c) 2014年 网信金融集团. All rights reserved.
//

#import "ChatRecent.h"
#import "CFTextView.h"
#import "CFTextAttachment.h"

@implementation ChatRecent

- (void)setMessageBody:(NSString *)contentString
{
    if (contentString.length == 0) {
        return;
    }
    NSString *firststr = @"&lt;img class=&quot;emotioneee&quot; src=&quot;/wxfront/resource/img/arclist/";
    NSString *laststr = @"&quot; border=&quot;0&quot; /&gt;";
    contentString=[contentString stringByReplacingOccurrencesOfString:firststr withString:@"<"];
    contentString=[contentString stringByReplacingOccurrencesOfString:laststr withString:@">"];
    _messageBody = contentString;
    
    NSString* pattern = @"<[1-9][0-9]?.gif>";
    
    NSRegularExpression* regx = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSDictionary* emotionDic = [self getgitPlist];
    
    NSMutableDictionary* gifEomtionDict = [[NSMutableDictionary alloc] init];
    [regx enumerateMatchesInString:contentString options:NSMatchingReportProgress range:NSMakeRange(0, contentString.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        NSString* resultString = [contentString substringWithRange:result.range];
        NSString* gifName = emotionDic[resultString];
        
        for (int i = 0; resultString.length > 2 && !gifName; i++) {
            resultString = [resultString substringWithRange:NSMakeRange(0, resultString.length - 1)];
            gifName = emotionDic[resultString];
        }
        
        if (gifName) {
            gifEomtionDict[NSStringFromRange(NSMakeRange(result.range.location, resultString.length))] = gifName;
        }
    }];
    
    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:contentString];
    NSMutableArray* ranges = [gifEomtionDict.allKeys mutableCopy];
    [ranges sortUsingComparator:^NSComparisonResult(NSString* obj1, NSString* obj2) {
        NSRange range1 = NSRangeFromString(obj1);
        NSRange range2 = NSRangeFromString(obj2);
        
        if (range1.location < range2.location) {
            return NSOrderedDescending;
        }
        
        return NSOrderedAscending;
    }];
    
    for (NSString* rangeString in ranges) {
        CFTextAttachment* attachment = [[CFTextAttachment alloc] init];
        attachment.bounds = gifRect;
        attachment.gifName = gifEomtionDict[rangeString];
        NSAttributedString* attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
        [attributedString replaceCharactersInRange:NSRangeFromString(rangeString) withAttributedString:attachmentString];
    }
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, attributedString.length)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attributedString.length)];
    
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.lineSpacing = 8;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
    
    self.attributedString = attributedString;
    
}

- (void)setAttributedString:(NSMutableAttributedString *)attributedString
{
    if (attributedString.length == 0) {
        return;
    }
    _attributedString = attributedString;
}
-(NSDictionary *)getgitPlist{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    //目录下的文件夹名字'gifhlq'
    NSString *pathFile = [path stringByAppendingPathComponent:@"gifhlq"];
    
    //判断有没有文件夹
    BOOL isDir =NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:pathFile isDirectory:&isDir];
    if ( !(isDir ==YES && existed == YES) ){
        //如果没有文件夹则创建
        [fileManager createDirectoryAtPath:pathFile  withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        //删除文件夹
        //[fileManager removeItemAtPath:pathFile error:nil];
    }
    
    //在目录文件夹下找相应文件'bbb.plist'
    NSString *filename=[pathFile stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",@"EmotionGifList"]];
    if (![fileManager fileExistsAtPath:filename]) {
        //如果没有文件，添加新内容，生成新文件
        NSMutableDictionary *dic;//(内容随便写的)
        
        for (int i = 1; i<75; i++) {
            [dic setValue:[NSString stringWithFormat:@"%d.gif",i] forKey:[NSString stringWithFormat:@"/[%d]",i]];
        }
        [dic writeToFile:filename atomically:YES];
        return dic;
    }else{
        //如果有文件，获取文件夹文件
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filename];
        return dic;
        WXLog(@"%@",dic);
    }
    return nil;
}


@end
